package com.qt.service.message.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qt.enums.ApiExceptionEnum;
import com.qt.mapper.SessionMapper;
import com.qt.pojo.entity.message.SystemNotice;
import com.qt.pojo.entity.message.UserNotice;
import com.qt.pojo.entity.user.Session;
import com.qt.service.message.SessionService;
import com.qt.service.message.SystemNoticeService;
import com.qt.service.message.UserNoticeService;
import com.qt.utils.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author pgw
 * @version 1.0
 * @description
 * @date Create by 2023/9/20 22:16
 */
@Service
public class SessionServiceImpl  extends ServiceImpl<SessionMapper , Session>  implements SessionService {

    @Autowired
    private SystemNoticeService systemNoticeService;

    @Autowired
    private UserNoticeService userNoticeService;

    /**
     * 检查是否异地登录
     * @param userId
     */
    @Async
    @Override
    public void checkRemoteLogin(String userId) {
        LambdaQueryWrapper<Session> sessionQueryWrapper = new LambdaQueryWrapper<>();
        sessionQueryWrapper.eq(Session::getUserId ,userId)
                .orderByDesc(Session::getGmtCreate)
                .last("limit 2");
        List<Session> sessionList = this.list(sessionQueryWrapper);
        if(sessionList == null || sessionList.size() < 2){
            return;
        }

        //判断异地登录
        Session nowSession = sessionList.get(0);
        Session lastSession = sessionList.get(1);

        if(nowSession.getIp().equals(lastSession.getIp())){
            return;
        }

        String remoteLoginContent = this.getRemoteLoginContent(lastSession.getIp(), nowSession.getIp(), nowSession.getGmtCreate());
        AssertUtils.notNull(remoteLoginContent , ApiExceptionEnum.CONTENT_IS_BLANK);

        if(StringUtils.isEmpty(remoteLoginContent)){
            return;
        }
        SystemNotice systemNotice = new SystemNotice();
        //异地登录，发通知给用户
        boolean isSaveOk = systemNoticeService.save(systemNotice
                .setContent(remoteLoginContent)
                .setTitle("账号异地登录通知(Account Remote Login Notice)")
                .setReceiveId(userId)
                .setState(0));
        if(isSaveOk){
            UserNotice userNotice = new UserNotice()
                    .setType("system")
                    .setSystemNoticeId(systemNotice.getId())
                    .setReceiveId(userId)
                    .setState(0);
            boolean isOk = userNoticeService.save(userNotice);
            if(isOk){
                systemNotice.setState(1);
                systemNoticeService.updateById(systemNotice);
            }
        }



    }

    private String getRemoteLoginContent(String oldIp, String newIp, Date loginDate) {
        String dateStr = DateUtil.format(loginDate, "yyyy-MM-dd HH:mm:ss");
        StringBuilder sb = new StringBuilder();
        sb.append("亲爱的用户，您好！您的账号于").append(dateStr);
        String addr = null;
        try {
            String newRes = HttpUtil.get("https://whois.pconline.com.cn/ipJson.jsp?ip=" + newIp + "&json=true");
            JSONObject newResJson = JSONUtil.parseObj(newRes);
            addr = newResJson.getStr("addr");

            String newCityCode = newResJson.getStr("cityCode");

            String oldRes = HttpUtil.get("https://whois.pconline.com.cn/ipJson.jsp?ip=" + oldIp + "&json=true");
            JSONObject oldResJson = JSONUtil.parseObj(oldRes);

            String oldCityCode = oldResJson.getStr("cityCode");

            if (newCityCode == null || oldCityCode == null || newCityCode.equals(oldCityCode)) {
                return null;
            }

        } catch (Exception ignored) {
            return null;
        }
        if (!StringUtils.isEmpty(addr)) {
            sb.append("在【")
                    .append(addr)
                    .append("】");
        }
        sb.append("登录，登录IP为：【")
                .append(newIp)
                .append("】，若非本人操作，请立即修改密码。")
                .append("\n\n")
                .append("Hello! Dear user, Your account was logged in in");

        if (!StringUtils.isEmpty(addr)) {
            sb.append(" 【")
                    .append(addr)
                    .append("】 on ")
                    .append(dateStr)
                    .append(". If you do not operate by yourself, please change your password immediately.");
        }

        return sb.toString();
    }
}
